'''
Created on 19.05.2014

@author: Wolfgang
'''

import MFRC522
import databaseApi
import signal
import sys
import RPi.GPIO as GPIO
import time
import logging

# Here the main program starts with reading and so on..
logging.basicConfig(filename='/var/log/runGame.log', level=logging.INFO, format='%(asctime)s %(message)s');
continue_reading = True
connection = databaseApi.connect()
logging.info('Start Game');
logging.info('Fetch Active Race');
try:
    raceId = databaseApi.getActiveCompetition(connection)
except:
    logging.error('No Active Race');
    sys.exit()

logging.info('Found Race: '+str(raceId));
tagUId = ''
tagUId_old = ''
# Capture SIGINT
def end_read(signal,frame):
    global continue_reading
    global connection
    continue_reading = False
    databaseApi.finish(connection)
    GPIO.output(18,False)
    MFRC522.MFRC522_cleanUp
    logging.info('Terminated Game');
  
signal.signal(signal.SIGINT, end_read)
signal.signal(signal.SIGTERM, end_read)
MIFAREReader = MFRC522.MFRC522()
GPIO.setup(18, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)
GPIO.output(18,True)
while continue_reading:
    (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
    if status == MIFAREReader.MI_OK:
        logging.debug('Card Detected');
        (status,backData) = MIFAREReader.MFRC522_Anticoll()
        if status == MIFAREReader.MI_OK:
            tagUId = str(backData[0])+"@"+str(backData[1])+"@"+str(backData[2])+"@"+str(backData[3])+"@"+str(backData[4])
            logging.debug("Previous Card UID: "+ tagUId_old)
            logging.debug("Card read UID: "+tagUId)
            if tagUId != tagUId_old:
                tagUId_old = tagUId
                logging.info('Insert Lap raceId/tagId: '+str(raceId)+' / '+tagUId);
                databaseApi.insertLap(tagUId, raceId, connection)
                GPIO.output(16,True)
                time.sleep(3)
                GPIO.output(16,False)
                logging.debug('inserted lap for '+tagUId);